package com.example.casper.Experiment2024.fragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.activity.PublishActivity;
import com.example.casper.Experiment2024.adapter.PublishAdapter;
import com.example.casper.Experiment2024.entity.LocationInfo;
import com.example.casper.Experiment2024.utils.BookModel;
import com.example.casper.Experiment2024.utils.SharedPrefs;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.util.List;

public class PublishListFragment extends Fragment {

    private static final String TAG = "BookListFragment";
    private ProgressDialog dialog;
    private TencentLocationManager mLocationManager;
    private PublishAdapter adapter;
    private RecyclerView content;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_publish, container, false);

        SharedPrefs sharedPrefs = new SharedPrefs(requireContext());
        Boolean isFirst = (Boolean) sharedPrefs.get("isFirst", true);
        if (isFirst) {
            BookModel.init(requireContext());
            sharedPrefs.put("isFirst", false);
        }

        mLocationManager = TencentLocationManager.getInstance(requireContext());

        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION}, 0x99);


        adapter = new PublishAdapter();
        content = view.findViewById(R.id.content);
        content.setAdapter(adapter);

        view.findViewById(R.id.add).setOnClickListener(v -> {
            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }
            dialog = new ProgressDialog(requireContext());
            dialog.setTitle("温馨提示");
            dialog.setMessage("定位中...");
            dialog.show();
            TencentLocationRequest request = TencentLocationRequest.create();
            request.setGpsFirst(true);
            mLocationManager.requestSingleFreshLocation(request, new TencentLocationListener() {
                @Override
                public void onLocationChanged(TencentLocation location, int error, String reason) {
                    /**
                     * location - 新的位置, *可能*来自缓存. 定位失败时 location 无效或者为 null
                     * error - 错误码, 仅当错误码为 TencentLocation.ERROR_OK 时表示定位成功, 为其他值时表示定位失败
                     * reason - 错误描述, 简要描述错误原因
                     */
                    if (dialog != null) {
                        dialog.dismiss();
                        dialog = null;
                    }
                    Log.d(TAG, "onLocationChanged() called with: location = [" + location + "], error = [" + error + "], reason = [" + reason + "]");
                    Intent intent = new Intent(requireContext(), PublishActivity.class);
                    intent.putExtra("title", location.getName());
                    intent.putExtra("lat", location.getLatitude());
                    intent.putExtra("lon", location.getLongitude());
                    startActivity(intent);
                }

                @Override
                public void onStatusUpdate(String name, int status, String desc) {
                    /**
                     * name - 设备名, GPS, WIFI, CELL 中的某个
                     * status - 状态码, STATUS_ENABLED, STATUS_DISABLED, STATUS_UNKNOWN, STATUS_GPS_AVAILABLE, STATUS_GPS_UNAVAILABLE, STATUS_DENIED中的某个 在使用status之前,请先按照name进行区分
                     * desc - 状态描述
                     */
                    Log.d(TAG, "onStatusUpdate() called with: name = [" + name + "], status = [" + status + "], desc = [" + desc + "]");
                    if (dialog != null) {
                        dialog.dismiss();
                        dialog = null;
                    }
                }
            }, Looper.getMainLooper());
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences preferences = requireContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        String json = preferences.getString("points", "[]");
        List<LocationInfo> infos = JSON.parseArray(json, LocationInfo.class);
        adapter.submitList(infos);
    }
}